package com.kingmed.kmss.common.service.sys.impl;

import com.kingmed.kmss.common.service.sys.SerialNoService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.concurrent.TimeUnit;

/**
 * 序列号生成实现类(unused)
 */
@Service
public class SerialNoServiceImpl implements SerialNoService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    static final int DEFAULT_LENGTH = 4;

    /*** 得到10位的序列号,长度不足10位,前面补0
     *
     * @paramseq
     * @return
     */
    public static String getSequence(long seq) {
        String str = String.valueOf(seq);
        int len = str.length();
        if (len >= DEFAULT_LENGTH) {//取决于业务规模,应该不会到达10
            return str;
        }
        int rest = DEFAULT_LENGTH - len;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < rest; i++) {
            sb.append('0');
        }
        sb.append(str);
        return sb.toString();
    }

    /**
     * 自增
     *
     * @param key
     * @param liveTime
     * @return
     */
    @Override
    public Long incr(String key, long liveTime) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();
        if ((null == increment || increment.longValue() == 0) && liveTime > 0) {//初始设置过期时间
            entityIdCounter.expire(liveTime, TimeUnit.HOURS);
        }
        return increment;
    }

    @Override
    public String getOrder() {
        String order = "";
        String dateString = "";
//        String dateString = DateUtils.formatDate(newDate());
        Long incr = this.incr("deviceRepair" + dateString, 24);
        if (incr == 0) {
            incr = this.incr("deviceRepair" + dateString, 24);
        }
        DecimalFormat df = new DecimalFormat("00000");
        String[] drs = dateString.split("-");
        for (int i = 1; i < drs.length; i++) {
            order += drs[i];
        }
        order = "X" + order + df.format(incr);
        return order;
    }

}